package com.samuel.blog.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

/**
 * 工具类 -- httpClient
 * @author kaiji
 *
 */
@SuppressWarnings("deprecation")
public class HttpClientUtil {

	public static String httpGet(String url, Map<String, String> params) {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		Iterator<String> keysIte = params.keySet().iterator();
		int index = 0;
		while (keysIte.hasNext()) {
			String key = keysIte.next();
			if (index == 0) {
				url = url + "?" + key + "=" + params.get(key);
			} else {
				url = url + "&" + key + "=" + params.get(key);
			}
			index++;
		}
		HttpGet httpget = new HttpGet(url);
		CloseableHttpResponse response = null;
		StringBuilder result = new StringBuilder();

		// 设置请求和传输超时时间5s,设置cookie策略
		RequestConfig requestconfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000)
				.setCookieSpec(CookieSpecs.BEST_MATCH).build();
		httpget.setConfig(requestconfig);

		try {
			response = httpClient.execute(httpget);
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				InputStream is = entity.getContent();
				BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
				String line;
				while ((line = br.readLine()) != null) {
					result.append(line);
					result.append("\n");
				}
				is.close();
				br.close();
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				response.close();
				httpClient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return result.toString();
	}

	public static String httpPost(String url, String body) {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost(url);
		CloseableHttpResponse response = null;
		String result = null;

		try {
			StringEntity stringEntity = new StringEntity(body, "UTF-8");
			httpPost.setEntity(stringEntity);
			response = httpClient.execute(httpPost);
			HttpEntity entity = response.getEntity();

			if (entity != null) {
				result = EntityUtils.toString(entity, "UTF-8");
			}
			EntityUtils.consume(entity);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				response.close();
				httpClient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return result;
	}

	public static String httpPost(String url, Map<String, String> params) {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost(url);
		CloseableHttpResponse response = null;
		String result = null;

		try {
			List<NameValuePair> nvps = new ArrayList<NameValuePair>();
			for(String key : params.keySet()){
			    nvps.add(new BasicNameValuePair(key, params.get(key)));  
			}
	        httpPost.setEntity(new UrlEncodedFormEntity(nvps,"UTF-8"));  
			response = httpClient.execute(httpPost);
			HttpEntity entity = response.getEntity();

			if (entity != null) {
				result = EntityUtils.toString(entity, "UTF-8");
			}
			EntityUtils.consume(entity);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				response.close();
				httpClient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return result;
	}

	public static String getBodyString(BufferedReader br) {
		String inputLine;
		String str = "";
		try {
			while ((inputLine = br.readLine()) != null) {
				str += inputLine;
			}
			br.close();
		} catch (IOException e) {
			System.err.println("IOException: " + e);
		}
		return str;
	}

	/**
	 * 设置url以及键值对参数
	 * 
	 * @param url
	 * @param params
	 * @return
	 */
	public static String getUrlWithParams(String url, Map<String, String> params) {
		Iterator<String> keysIte = params.keySet().iterator();
		int index = 0;
		while (keysIte.hasNext()) {
			String key = keysIte.next();
			if (index == 0) {
				url = url + "?" + key + "=" + params.get(key);
			} else {
				url = url + "&" + key + "=" + params.get(key);
			}
			index++;
		}
		return url;
	}
	

	/**
	 * 按照一定顺序设置url以及键值对参数
	 * 
	 * @param url
	 * @param params
	 * @param orderList
	 * @return
	 */
	public static String getUrlWithParams(String url, Map<String, String> params, List<String> orderList) {
		int index = 0;
		for (String key : orderList) {
			if (index == 0) {
				url = url + "?" + key + "=" + params.get(key);
			} else {
				url = url + "&" + key + "=" + params.get(key);
			}
			index++;
		}
		return url;
	}

	/**
	 * 下载文件
	 * @param url 下载链接
	 * @param dst 保存路径
	 * @return
	 */
	public static boolean downLoad(String url, String dst) {
		CloseableHttpClient httpClient = null;
		HttpGet httpGet = null;
		CloseableHttpResponse httpResponse = null;
		try {
			httpClient = HttpClients.createDefault();
			httpGet = new HttpGet(url);
			httpResponse = httpClient.execute(httpGet);
			HttpEntity entity = httpResponse.getEntity();
			InputStream in = entity.getContent();
			long length = entity.getContentLength();
			if (length <= 0) {
				System.out.println("下载文件不存在！");
				return false;
			}
			OutputStream out = new FileOutputStream(new File(dst));
			byte[] data = new byte[1024 * 1024];
			int index = 0;
			while ((index = in.read(data)) != -1) {
				out.write(data, 0, index);
			}
			in.close();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		} finally {
			try {
				httpResponse.close();
				httpClient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return true;
	}
	
	public static void main(String[] args) {
		Map<String, String> mapParam = new HashMap<>();
		mapParam.put("xmlParam", "11");
		System.out.println(HttpClientUtil.httpGet("http://csm.hb189.mobi/wxapi/pay/unifiedorder", mapParam));
	}
}
